﻿using Scorpicore.Data;
using Scorpicore.Models;
using Scorpicore.MVC.Models;
using Scorpicore.MVC.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using System.Net;
using System.Collections.Specialized;

namespace Scorpicore.MVC.Controllers
{

        [ValidateInput(false)] 
    public class BanknoteController : Controller
    {

        IUnitOfWork db;

        public BanknoteController(IUnitOfWork db)
        {
            this.db = db;
        }

        //
        // GET: /Banknote/
        public ActionResult Index()
        {
            return RedirectToAction("UserError","Home");
        }

        //
        // GET: /Banknote/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Banknote/Create
        [Authorize]
        public ActionResult CreateTrack()
        {
            ViewBag.PlaceId = new SelectList(db.Places.All().OrderBy(p => p.Name), "Id", "Name");
            //ViewBag.Denomination = new SelectList(new List<string>() { "два лв.", "пет лв.", "десет лв.", "двадесет лв.", "петдесет лв.", "сто лв." });
            return View();
        }
        //
        // POST: /Banknote/Create
        [Authorize]
        [HttpPost]
        public ActionResult CreateTrack(AddNewTrackViewModel model)
        {

            var user = db.Users.All().FirstOrDefault(u => u.UserName == User.Identity.Name);
            Track realTrack = new Track();
            if (ModelState.IsValid)
            {
                Banknote banknote = db.Banknotes.All().FirstOrDefault(b => b.Letters == model.BanknoteLetters && b.SerialNumber == model.BanknoteSerialNumber);
                string denomination = model.Denomination;
                Place lastPlace = db.Places.All().FirstOrDefault(p => p.Id == model.PlaceId);
                Denomination denom;
                string banknoteImgUrl = string.Empty;
                switch (denomination)
                {
                    case "два лв.": denom = Denomination.Two; banknoteImgUrl = "../../img/BanknoteImages/two.png"; break;
                    case "пет лв.": denom = Denomination.Five; banknoteImgUrl = "../../img/BanknoteImages/five.png"; break;
                    case "десет лв.": denom = Denomination.Ten; banknoteImgUrl = "../../img/BanknoteImages/ten.png"; break;
                    case "двадесет лв.": denom = Denomination.Twenty; banknoteImgUrl = "../../img/BanknoteImages/twenty.png"; break;
                    case "петдесет лв.": denom = Denomination.Fifty; banknoteImgUrl = "../../img/BanknoteImages/fifty.png"; break;
                    case "сто лв.": denom = Denomination.Hundred; banknoteImgUrl = "../../img/BanknoteImages/hundred.png"; break;
                    default: denom = Denomination.Two; banknoteImgUrl = "../../img/BanknoteImages/two.png";
                        break;
                }

                if (banknote == null)
                {
                    banknote = new Banknote()
                    {
                        Denomination = denom,
                        ImageUrl = banknoteImgUrl,
                        LastPlace = lastPlace.Name,
                        Letters = model.BanknoteLetters,
                        SerialNumber = model.BanknoteSerialNumber
                    };
                    db.Banknotes.Add(banknote);
                    db.SaveChanges();
                }
                else
                {
                    var banknoteTracks = banknote.Tracks.OrderByDescending(t => t.Date).ToList();
                    var lastTrack = banknoteTracks[0];
                    if (lastTrack.User.Id == User.Identity.GetUserId() && lastTrack.Date < DateTime.Now.AddDays(30))
                    {
                        return RedirectToAction("UserError", "Home", new ErrorViewModel() { ErrorMessage = "Опитвате се да въведете последната от вас регистрирана банкнота!" });
                    }
                }

                Track track = new Track()
                {
                    Banknote = banknote,
                    Date = DateTime.Now,
                    Message = model.Message,
                    Place = lastPlace,
                    PlaceId = lastPlace.Id,
                    User = user
                };
                realTrack = track;
                
                db.Tracks.Add(track);
                db.SaveChanges();

                banknote.Tracks.Add(track);
                db.SaveChanges();

                user.Banknotes.Add(banknote);
                db.SaveChanges();

                var newBanknote = new CheckBanknoteIsExistViewModel
                {
                    Letters = banknote.Letters,
                    SerialNumber = banknote.SerialNumber
                };               

                return ChooseBanknote(newBanknote);
                //return RedirectToAction("CheckBanknote", new { letters=model.BanknoteLetters, serialNumber=model.BanknoteSerialNumber});
            }

            ViewBag.PlaceId = new SelectList(db.Places.All().OrderBy(p => p.Name), "Id", "Name", realTrack.PlaceId);
            return View(model);
        }

        //
        // GET: /Banknote/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Banknote/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Banknote/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Banknote/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult RedirectFromGrid(CheckBanknoteIsExistViewModel banknote)
        {
            return ChooseBanknote(banknote);
        }

        public ActionResult ChooseBanknote()
        {
            return View();
        }

        //public ActionResult CheckBanknote()
        //{
        //    return View();
        //}

        [HttpPost]
        public ActionResult ChooseBanknote(CheckBanknoteIsExistViewModel banknote)
        {
            if (ModelState.IsValid)
            {
                CheckBanknoteViewModel model = new CheckBanknoteViewModel();

                bool hasBanknote = model.LoadBanknote(banknote.Letters, banknote.SerialNumber);
                if (hasBanknote)
                {
                    return View("CheckBanknote", model);
                }
                else
                {
                    return View("ChooseBanknoteMissing", banknote);
                }
            }

            return View(banknote);
        }
    }
}
